package com.gin.kotlin.no_gay_alliance.fragment.main.usercenter

import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import androidx.core.view.MenuProvider
import com.gin.kotlin.no_gay_alliance.R
import com.gin.kotlin.no_gay_alliance.activity.UserCenterActivity
import com.gin.kotlin.no_gay_alliance.adapter.user.IpLocationAdapter
import com.gin.kotlin.no_gay_alliance.adapter.user.IpLocationRangeAdapter
import com.gin.kotlin.no_gay_alliance.app.App
import com.gin.kotlin.no_gay_alliance.database.entity.IpLocationHistory
import com.gin.kotlin.no_gay_alliance.databinding.FragmentUserCenterTabIpLocationBinding
import com.gin.kotlin.no_gay_alliance.model.IpLocationRange
import com.gin.kotlin.no_gay_alliance.model.UserDetailModel

class UserCenterTabIpLocationFragment : AbstractUserCenterTabFragment<FragmentUserCenterTabIpLocationBinding>, MenuProvider {
    constructor() : super()
    constructor(data: UserDetailModel?) : super(data)

    private lateinit var data: List<IpLocationHistory>
    private var mode = Mode.LIST

    override fun onCreateView() {
        this.data = App.INSTANCE.database.ipLocationHistoryDao().queryByUserId(userDetail.userId!!)
        listAdapter()
    }


    override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
        menuInflater.inflate(R.menu.ip_location, menu)
    }

    override fun onPrepareMenu(menu: Menu) {
        super.onPrepareMenu(menu)
        val list = menu.findItem(R.id.mi_ip_location_list)
        val collapse = menu.findItem(R.id.mi_ip_location_collapse)

        when (mode) {
            Mode.LIST -> {
                list.isVisible = false
                collapse.isVisible = true
            }

            Mode.COLLAPSE -> {
                list.isVisible = true
                collapse.isVisible = false
            }
        }
    }

    override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
        return when (menuItem.itemId) {
            // 展开模式
            R.id.mi_ip_location_list -> {
                mode = Mode.LIST
                listAdapter()
                invalidateOptionsMenu()
                true
            }
            // 折叠模式（范围）
            R.id.mi_ip_location_collapse -> {
                mode = Mode.COLLAPSE
                collapseAdapter()
                invalidateOptionsMenu()
                true
            }

            else -> false
        }
    }

    private fun invalidateOptionsMenu() {
        (requireActivity() as? UserCenterActivity)?.supportInvalidateOptionsMenu()
    }

    private fun listAdapter() {
        b?.recyclerView?.adapter = IpLocationAdapter(requireContext(), handler!!).also { it.replaceData(data.reversed()) }
    }

    private fun collapseAdapter() {
        b?.recyclerView?.adapter = IpLocationRangeAdapter(requireContext(), handler!!).also { it.replaceData(IpLocationRange.merge(data).reversed()) }
    }

    enum class Mode {
        LIST, COLLAPSE
    }
}